package edu.xhu;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bean.AlreadyBookBean;
import com.bean.UpdateBean;
import com.constant.Constant;
import com.data.LoginLibraryData;
import com.data.RenewBookData;
import com.net.ClientError;
import com.net.LoadData;
import com.net.RequestListener;
import com.net.RequestParameter;

import edu.xhu.util.DatabaseAdapter;
import edu.xhu.util.InstalApk;
import edu.xhu.view.LoadingDialog;
/**
 * 首页，9宮格主界面
 * @author swerit
 *
 */
public class XihuaClientActivity extends Activity {
	
	private XhuApplication application;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        initView();
        loadData();
    }
    private void loadData() {
    	
//    	SharedPreferences sp = getSharedPreferences("update", MODE_WORLD_READABLE);
//    	boolean bSelected = sp.getBoolean("update", false);
//    	
//    	if(bSelected == true) {
//    		return;
//    	}
    	
    	
    	// 检查是否有更新
		LoadData.loadData(Constant.CHECK_UPDATE, null, new RequestListener() {
			
			@Override
			public void onError(ClientError ed) {
				
			}
			
			@Override
			public void onComplete(Object obj) {
				UpdateBean bean = (UpdateBean) obj;
				
				SharedPreferences sp = getSharedPreferences("update", MODE_WORLD_READABLE);

				boolean bSelect = sp.getBoolean("update", false);
				if(bSelect == false) {
					InstalApk apk = new InstalApk(XihuaClientActivity.this, bean, true);
					apk.checkUpdate();
				}
				else {
					
					String version = sp.getString("version", "");
					// 有最新版本需要更新
					if(!bean.getVersion().equals(version)) {
						InstalApk apk = new InstalApk(XihuaClientActivity.this, bean, true);
						apk.checkUpdate();
						return;
					}
					
					long dTime = sp.getLong("time", 0);
					Calendar calendar = Calendar.getInstance();
					if(calendar.getTimeInMillis() - dTime > 1000 * 60 * 60 * 48) {
						InstalApk apk = new InstalApk(XihuaClientActivity.this, bean, true);
						apk.checkUpdate();
					}
					
				}
			}
		});
    }
    /**
     * 初始化界面
     */
    private void initView(){
    	application				= (XhuApplication) getApplication();
    	LinearLayout container = (LinearLayout) findViewById(R.id.container);
    	LayoutInflater inflater = LayoutInflater.from(this);
    	
    	//第一行
    	LinearLayout layout = new LinearLayout(XihuaClientActivity.this);
		layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		layout.setOrientation(LinearLayout.HORIZONTAL);
		
		View view = inflater.inflate(R.layout.main_item, null);
		ImageView img = (ImageView) view.findViewById(R.id.img);
		img.setImageResource(R.drawable.g1_1);
		TextView textView = (TextView) view.findViewById(R.id.control_name);
		textView.setText("图书馆");
		view.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(XihuaClientActivity.this, Library.class);
				startActivity(intent);
				
				//向服务器提交数据
				submitData(Constant.MODULE_LIBRARY + "");
			}
		});
		layout.addView(view);
		
		view = inflater.inflate(R.layout.main_item, null);
		img = (ImageView) view.findViewById(R.id.img);
		img.setImageResource(R.drawable.g1_2);
		textView = (TextView) view.findViewById(R.id.control_name);
		textView.setText("就业信息");
		view.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(XihuaClientActivity.this, EmploymentActivity.class);
				startActivity(intent);
				
				//向服务器提交数据
				submitData(Constant.MODULE_JOB + "");
			}
		});
		layout.addView(view);
		
		container.addView(layout);
		
		//第二行
		layout = new LinearLayout(XihuaClientActivity.this);
		layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		layout.setOrientation(LinearLayout.HORIZONTAL);
		
		view = inflater.inflate(R.layout.main_item, null);
		img = (ImageView) view.findViewById(R.id.img);
		img.setImageResource(R.drawable.g2_1);
		textView = (TextView) view.findViewById(R.id.control_name);
		textView.setText("教务系统");
		view.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(XihuaClientActivity.this,
						LoginActivity.class);
				startActivity(intent);
				
				//向服务器提交数据
				submitData(Constant.MODULE_EDU_SYSTEM + "");
			}
		});
		layout.addView(view);
		
		view = inflater.inflate(R.layout.main_item, null);
		img = (ImageView) view.findViewById(R.id.img);
		img.setImageResource(R.drawable.g2_2);
		textView = (TextView) view.findViewById(R.id.control_name);
		textView.setText("反馈");
		view.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				//Intent intent = new Intent(XihuaClientActivity.this, FeedbackActivity.class);
				Intent intent = new Intent(XihuaClientActivity.this, XiHuaActivity.class);
				startActivity(intent);
			}
		});
		layout.addView(view);
		container.addView(layout);
		
		//第三行
		layout = new LinearLayout(XihuaClientActivity.this);
		layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		layout.setOrientation(LinearLayout.HORIZONTAL);
		
		view = inflater.inflate(R.layout.main_item, null);
		img = (ImageView) view.findViewById(R.id.img);
		img.setImageResource(R.drawable.g3_1);
		textView = (TextView) view.findViewById(R.id.control_name);
		textView.setText("检查更新");
		view.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				LoadingDialog.showWindow(XihuaClientActivity.this);
				LoadData.loadData(Constant.CHECK_UPDATE, null, new RequestListener()
				{
					
					public void onError(ClientError ed)
					{
						Toast.makeText(XihuaClientActivity.this, "网络请求错误", 0).show();
						LoadingDialog.dismiss();
					}
					
					public void onComplete(Object obj)
					{
						LoadingDialog.dismiss();
						InstalApk instalApk = new InstalApk(XihuaClientActivity.this, (UpdateBean)obj, false);
						instalApk.checkUpdate();
					}
				});
				
			}
		});
		
		layout.addView(view);
		
		view = inflater.inflate(R.layout.main_item, null);
		img = (ImageView) view.findViewById(R.id.img);
		img.setImageResource(R.drawable.g3_2);
		textView = (TextView) view.findViewById(R.id.control_name);
		textView.setText("退出系统");
		view.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showQuitDialog();
				
//				RequestParameter parameter = new RequestParameter();
//				parameter.add("number", "312009070102221");
//				parameter.add("passwd", "19900630");
//				parameter.add("select", "cert_no");
//				parameter.add("returnUrl", "");
//				LoadData.loadData(Constant.LOGIN_LIBRARY_DATA, parameter, new RequestListener() {
//					
//					@Override
//					public void onError(ClientError ed) {
//						
//					}
//					
//					@Override
//					public void onComplete(Object obj) {
//						
//					}
//				});
				
			}
		});
		layout.addView(view);
		container.addView(layout);
    }
    
    private void showQuitDialog()
	{
		Dialog dlg = new AlertDialog.Builder(XihuaClientActivity.this)
		.setTitle("提示")
		.setMessage("是否退出程序")
		.setNeutralButton("是", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				LoadData.clear();
		    	finish();
			}
		})
		.setNegativeButton("否", new DialogInterface.OnClickListener() 	{
			
			public void onClick(DialogInterface dialog, int which) {
				
			}
		}).create();
		dlg.show();
	}
    
    private void submitData(String perCountValue){
    	//向服务器提交数据
		RequestParameter parameter = new RequestParameter();
		parameter.add("imei", application.getImei());
		parameter.add("channel", application.getChannel());
		parameter.add("per_count", perCountValue);
		LoadData.loadData(Constant.MODULE, parameter, null);
    }
    
    private void showHintDialog(){
    	Builder builder = new Builder(this);
    	builder.setTitle("提示")
    	.setMessage("是否清除本地所有的数据？")
    	.setPositiveButton("清除", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
						// 清除缓存
						DatabaseAdapter dbAdapter = new DatabaseAdapter(
								XihuaClientActivity.this);
						dbAdapter.openDatabase();
						dbAdapter.deleteAll();
						dbAdapter.closeDatabase();
						
						SharedPreferences spPreferences = getSharedPreferences("update", MODE_WORLD_WRITEABLE);
						Editor editor = spPreferences.edit();
						editor.putBoolean("update", false);
						editor.putString("version", "");
						editor.putLong("time", 0);
						editor.commit();
						
						Toast.makeText(XihuaClientActivity.this, "清除结束", 0).show();
			}
		}).setNegativeButton("不清除", null).create().show();
    }
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event)
	{
		if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP)
		{
//			showQuitDialog();
			return true;
		}
		return super.onKeyUp(keyCode, event);
		
	}
	
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		android.os.Process.killProcess(android.os.Process.myPid());
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
		case R.menu.clear:
			//清除缓存
			showHintDialog();
			break;
			
		case R.menu.about:
			//关于我们
			Intent intent = new Intent(XihuaClientActivity.this, AboutActivity.class);
			startActivityForResult(intent, 0);
			overridePendingTransition(R.anim.zoom_enter,
					R.anim.zoom_exit);//进入和退出时的效果
			break;
			
		case R.menu.help:
			//帮助
			Intent intent1 = new Intent(XihuaClientActivity.this, Help.class);
			startActivity(intent1);
			break;
			
		case R.menu.exit:
			//退出系统
			showQuitDialog();
			break;
		}
		
		return true;
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == KeyEvent.KEYCODE_BACK){
			exitBy2click();//调用双击退出函数
		}
		return false;
	}
	/**
	 * 双击退出函数
	 */
	private static Boolean isExit=false;
	private void exitBy2click(){
		Timer tExit=null;
		if(isExit==false){
			isExit=true;//准备退出
			Toast.makeText(this, "再按一次就退出掌中西华", Toast.LENGTH_SHORT).show();
			tExit=new Timer();
			tExit.schedule(new TimerTask(){

				@Override
				public void run() {
					// TODO Auto-generated method stub
					isExit=false;
				}
				
			}, 2000);
		}
		else{
			finish();
			System.exit(0);
		}
	}
	
	
}